package com.pig4cloud.pigx.user;

import org.bouncycastle.util.encoders.Hex;
import org.junit.jupiter.api.Test;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.Hash;
import org.web3j.crypto.Sign;

import java.math.BigDecimal;


/**
*
*
* @date:2022/8/9
*/public class test {

	/**
	 * @Description: Web3j签名验签
	 */

	// 钱包私钥
	private static final String priKey = "e62248374af86aa480f9cebd44f04cd02b915130d4fbda885a201488257b0a17";
	// 钱包地址
	private static final String walletAddress = "0x5ebacac108d665819398e5c37e12b0162d781398";

	@Test
	void test() {
		// 原文
//		String content = "青年人的责任重大！努力吧...";
		String content = "Hello Dapp";

		// 原文摘要字节数组
		byte[] contentHashBytes = Hash.sha3(content.getBytes());

		// 原文摘要16进制字符串
		String contentHashHex = Hex.toHexString(contentHashBytes);



		Credentials credentials = Credentials.create(priKey);
//		Sign.SignatureData signMessage = Sign.signPrefixedMessage(contentHashBytes, credentials.getEcKeyPair());
		Sign.SignatureData signMessage = Sign.signMessage(contentHashBytes, credentials.getEcKeyPair());
		System.out.println(Hex.toHexString(signMessage.getR()));
		System.out.println(Hex.toHexString(signMessage.getS()));
		System.out.println(Hex.toHexString(signMessage.getV()));

		// 签名后的字符串
		String signStr = "0x" + Hex.toHexString(signMessage.getR()) + Hex.toHexString(signMessage.getS()) + Hex.toHexString(signMessage.getV());
		System.out.println("signStr = " + signStr);
//		try {
//			// 原文摘要 添加 ETH签名头信息后再生成摘要
//			byte[] messageHash = Sign.getEthereumMessageHash(Hex.decode(contentHashHex));
//			Sign.
//
//			//通过摘要和签名后的数据，还原公钥
//			Sign.SignatureData signatureData = new Sign.SignatureData(signMessage.getV(), signMessage.getR(), signMessage.getS());
//			BigInteger publicKey = Sign.signedMessageHashToKey(messageHash, signatureData);
//
//			//还原地址 0x5E32cc9cF83e6f346830fc11e207ac4b91213f30
//			String parseAddress = "0x" + Keys.getAddress(publicKey);
//
//			System.err.println("Address：：" + parseAddress);
//		} catch (SignatureException e) {
//			e.printStackTrace();
//		}
	}

	@Test
	public void test1() {
		Integer integer = new Integer(0);
		do {
			this.testnext(integer);
			integer++;
			if (integer == 20) return;
		} while (true);
	}

	public void testnext(Integer integer) {

		if (integer.equals(5)) {
			return;
		}
		System.out.println("integer = " + integer);

	}

	@Test
	public void test2() {
		BigDecimal bigDecimal = new BigDecimal(1);
		BigDecimal bigDecimal1 = new BigDecimal(2);
		BigDecimal subtract = bigDecimal.subtract(bigDecimal1);
		System.out.println("subtract = " + subtract);
	}

}
